<template>
	<div class="container">
		<a-row :gutter="20" justify="end">
			<a-col :span="2" class="py-4 text-center">
				<a-space>
					<a-button @click="closeTab('/purchaseManage')">
						<close-outlined />关闭
					</a-button>
				</a-space>
			</a-col>
		</a-row>
		<h2 style="text-align: center;margin-bottom: 30px;">采购单</h2>
		<a-descriptions size="middle" title="申请单信息" bordered>
			<a-descriptions-item :span="2" label="项目名称">{{ applyPlanInfo.project?.name }}</a-descriptions-item>
			<a-descriptions-item label="申请单编号">{{ applyPlanInfo.code }}</a-descriptions-item>
			<a-descriptions-item label="申请人" :span="2">{{ applyPlanInfo.applier?.fullname }}</a-descriptions-item>
			<a-descriptions-item label="申请时间">{{ applyPlanInfo.create_time }}</a-descriptions-item>
			<template v-if="type == 'purchase'">
				<a-descriptions-item label="接收联系人">{{ applyPlanInfo.receiver || userlist.find(item => item.value === applyPlanInfo.receiver_id)?.label }}</a-descriptions-item>
				<a-descriptions-item label="联系人电话">{{ applyPlanInfo.receiver_tel }}</a-descriptions-item>
				<a-descriptions-item label="送达日期">{{ applyPlanInfo.deliver_time }}</a-descriptions-item>
				<a-descriptions-item label="送达地址">{{ applyPlanInfo.deliver_address }}</a-descriptions-item>
			</template>
			<template v-if="type == 'machineapply'">
				<a-descriptions-item label="现场联系人">{{ applyPlanInfo.receiver }}</a-descriptions-item>
				<a-descriptions-item label="联系人电话">{{ applyPlanInfo.receiver_tel }}</a-descriptions-item>
			</template>
			<template v-if="type == 'shangtong'">
				<a-descriptions-item label="预约技术指标">
					<span v-for="(item, ii) in applyPlanInfo.art_indexes" :key="ii" class="mr-5">
						{{ artIndexesGongHaos.find(i => i.value === item.gonghao_id)?.label }};
					</span>
				</a-descriptions-item>
			</template>
		</a-descriptions>
		<h3 style="margin: 10px 0;">
			<b>物资信息</b>
		</h3>
		<a-table v-if="type == 'purchase'" :data-source="applyPlanInfo.materials" :pagination="false" :columns="purchaseColumns.filter(item => item.dataIndex !== 'supplier_name' && item.key !== 'operation' && item.dataIndex !== 'contract_id' && item.dataIndex !== 'pendingQuantity' ) " :row-key="(record) => record.key">
			<template #bodyCell="{ column, index }">
				<template v-if="column.dataIndex === 'id'">{{ index + 1 }}</template>
			</template>
		</a-table>

		<a-table v-if="type === 'machineapply'" :data-source="applyPlanInfo.materials" :pagination="false" :columns="machineapplyColumns.filter(item => item.dataIndex !== 'supplier_name' && item.key !== 'operation' && item.dataIndex !== 'contract_id' && item.dataIndex !== 'pendingQuantity')" :row-key="(record) => record.key">
			<template #bodyCell="{ column, index }">
				<template v-if="column.dataIndex === 'id'">{{ index + 1 }}</template>
			</template>
		</a-table>

		<a-table v-if="type === 'shangtong'" :data-source="applyPlanInfo.materials" :pagination="false" :columns="shangtongColumns.filter(item => item.dataIndex !== 'supplier_name' && item.key !== 'operation' && item.dataIndex !== 'cg_fangliang' && item.dataIndex !== 'contract_id' && item.dataIndex !== 'pendingQuantity' && item.dataIndex !== 'art_indexes')">
			<!-- <template #bodyCell="{ column, index }">
					<template v-if="column.dataIndex === 'id'">
						{{ index+1 }}
					</template>
			</template>-->
		</a-table>

		<a-table v-if="type === 'auxiliary'" :data-source="applyPlanInfo.materials" :pagination="false" :columns="auxiliaryColumns.filter(item => item.dataIndex !== 'supplier_name' && item.key !== 'operation' && item.dataIndex !== 'cg_fangliang' && item.dataIndex !== 'contract_id' && item.dataIndex !== 'pendingQuantity' && item.dataIndex !== 'art_indexes')">
			<!-- <template #bodyCell="{ column, index }">
          <template v-if="column.dataIndex === 'id'">
            {{ index+1 }}
          </template>
      </template>-->
		</a-table>

		<h3 style="margin:12px 0">采购历史记录</h3>
		<a-row :gutter="20">
			<a-table :pagination="false" :columns="purchaseHistoryColumns" row-key="id" :data-source="purchasedOrderList">
				<template #bodyCell="{ column, record, index }">
					<template v-if="column.key === 'operation'">
						<a-space v-if="currentEditItemId !== record.id">
							<!--							<a-button v-if="!record.materials.filter(item => item.shipped > 0).length" type="link" @click="handleEdit(record)">-->
							<!--								<edit-outlined />修改-->
							<!--							</a-button>-->
							<a-button v-if="!record.materials.filter(item => item.shipped > 0).length" type="link" style="color:#ff7875" @click="handleDel(record.id, index)">
								<delete-outlined />删除
							</a-button>
						</a-space>
						<!--						<a-space v-else>-->
						<!--							<a-button type="link" html-type="submit" @click="handleCancelEdit">-->
						<!--								<reload-outlined />取消修改-->
						<!--							</a-button>-->
						<!--						</a-space>-->
					</template>
				</template>
				<template #expandedRowRender="{ record }">
					<a-table :columns="innerColumns" :data-source="record.materials" :pagination="false">
						<template #bodyCell="{ column, index }">
							<template v-if="column.dataIndex === 'part' && type === 'shangtong'">{{ (applyPlanInfo.materials[0].gonghao?.name || '') + ((applyPlanInfo.materials[0].partInfo)?.name || '') }}</template>
							<template v-if="column.dataIndex === 'model' && type === 'shangtong'">{{ (applyPlanInfo.materials[0].material?.name || '') + ((applyPlanInfo.materials[0].material)?.model || '') }}</template>
							<template v-if="column.dataIndex === 'art_indexes' && type === 'shangtong'">
								<span v-for="(item, ii) in record.materials[index]?.art_indexes" :key="ii" class="mr-5">
									{{ artIndexesGongHaos.find(i => i.value === item.gonghao_id)?.label }};
								</span>
							</template>
							<template v-if="column.dataIndex === 'cg_fangliang'">{{ record.materials[index].fangliang }}</template>
						</template>
					</a-table>
				</template>
			</a-table>
		</a-row>

		<div v-if="!showCreateForm" style="margin-top: 24px;">
			<a-row :gutter="20">
				<a-col :span="24" class="py-4 text-center">
					<a-space>
						<a-button v-permission="129" type="primary" @click="handleAdd">创建采购申请</a-button>
						<a-button @click="closeTab('/purchaseManage')">
							<close-outlined />关闭
						</a-button>
					</a-space>
				</a-col>
			</a-row>
			<!-- <a-button v-permission="129" type="primary" @click="handleAdd">创建采购申请</a-button>
			<a-button style="margin-left: 10px;" @click="closeTab('/purchaseManage')">
				<close-outlined />关闭
			</a-button> -->
		</div>

		<template v-if="showCreateForm">
			<a-form ref="formRef" :model="formState" @finish="handleSave">
				<div style="margin-top: 24px;">
					<a-row :gutter="20">
						<a-col :span="6">
							<a-form-item label="送达地址" name="deliver_address" :rules="{ required: true, message: '请输入送达地址' }">
								<a-input v-model:value="formState.deliver_address" placeholder="请输入送达地址" />
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item label="送达日期" name="deliver_time" :rules="{ required: true, message: '请输入送达时间' }">
								<a-date-picker v-model:value="formState.deliver_time" value-format="YYYY-MM-DD HH:mm:ss" show-time style="width:100%" />
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :gutter="20" style="padding-top: 24px;">
						<a-col :span="6">
							<a-form-item label="联系人" name="receiver_id" :rules="{ required: true, message: '请选择接收联系人' }">
								<a-select v-model:value="formState.receiver_id" :show-search="true" placeholder="请选择接收联系人" :options="userlist" option-filter-prop="label" @change="changeUser"></a-select>
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item label="联系人电话" name="receiver_tel" :rules="{ required: true, message: '请输入联系人电话' }">
								<a-input v-model:value="formState.receiver_tel" placeholder="请输入联系人电话" disabled />
							</a-form-item>
						</a-col>
					</a-row>
				</div>
				<a-col :span="24">
					<h1 style="margin: 30px 0">本次采购物资清单</h1>
					<div v-if="showAddBtn" class="table-toolbar mb-3">
						<a-space>
							<a-button type="primary" @click="addMaterialModel">
								<plus-outlined />新增
							</a-button>
						</a-space>
					</div>
					<a-table v-if="type === 'purchase'" :pagination="false" :data-source="formState.materials" :columns="purchaseColumns" :row-key="(record) => record.key">
						<template #bodyCell="{ column, record, index }">
							<template v-if="column.dataIndex === 'id'">{{ index + 1 }}</template>
							<template v-if="column.dataIndex === 'name'">
								<a-form-item :name="['materials', index, 'source_id']" :rules="{ required: true, message: '请选择材料名称' }">
									<a-select v-model:value="formState.materials[index].source_id" :show-search="true" placeholder="请选择材料名称" allow-clear :options="sourceOptions" style="width:100%" @change="handleSourceChange(record)">
										<template #title="{ label }">{{ label }}</template>
									</a-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'model'">
								<a-form-item :name="['materials', index, 'id']" :rules="{ required: true, message: '请选择规格' }">
									<a-select v-model:value="formState.materials[index].id" :show-search="true" placeholder="请选择" :options="modelOptions[record.source_id]" allow-clear :field-names="{ value: 'id', label: 'model' }" style="width:100%" @change="handleModelChange(record)"></a-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'unit'">
								<a-form-item :name="['materials', index, 'unit']" :rules="{ required: true, message: '请选择计量单位' }">
									<a-select v-model:value="formState.materials[index].unit" :show-search="true" placeholder="请选择" :options="unitOptions[record.id]" :field-names="{ value: 'name' }" style="width:100%" @change="handleUnitChange(record)"></a-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'contract_id'">
								<a-form-item :name="['materials', index, 'contract_id']" :rules="{ required: true, message: '请选择合同' }">
									<a-select v-model:value="formState.materials[index].contract_id" :show-search="true" placeholder="请选择" :options="(contractByMaterialOptions[record.id] || []).filter(item => item.supplier_id === record.supplier_id)" :field-names="{ value: 'id', label: 'name' }" style="width:100%" @change="handleContractChange(record)"></a-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'quantity'">
								<a-form-item :name="['materials', index, 'quantity']" :rules="{ required: true, message: '请输入数量' }" @change="handleQuantityChange(record)">
									<a-input-number v-model:value="formState.materials[index].quantity" placeholder="请输入数量" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'supplier_name'">
								<a-form-item :name="['materials', index, 'supplier_id']" :rules="{ required: true, message: '请选择供应商' }">
									<a-select v-model:value="formState.materials[index].supplier_id" :show-search="true" placeholder="请选择" :options="supplierByMaterialOptions[record.id]" allow-clear :field-names="{ value: 'id', label: 'company_name' }" style="width:100%" @change="handleSupplierChange(formState.materials[index])"></a-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'memo'">
								<a-form-item :name="['materials', index, 'memo']">
									<a-input v-model:value="formState.materials[index].memo" placeholder="请输入备注" />
								</a-form-item>
							</template>
							<template v-else-if="column.key === 'operation'">
								<a-space>
									<a-popconfirm title="确定要删除当前材料吗？" ok-text="是" cancel-text="否" @confirm="deleteMaterialModel(index)">
										<a-button type="link" style="color:#ff7875">
											<delete-outlined />删除
										</a-button>
									</a-popconfirm>
								</a-space>
							</template>
						</template>
					</a-table>
					<a-col v-if="type === 'machineapply'">
						<a-table :pagination="false" :data-source="formState.materials" :columns="machineapplyColumns" :row-key="(record) => record.key">
							<template #bodyCell="{ column, record, index }">
								<template v-if="column.dataIndex === 'id'">{{ index + 1 }}</template>
								<template v-if="column.dataIndex === 'name'">
									<a-form-item :name="['materials', index, 'source_id']" :rules="{ required: true, message: '请选择材料名称' }">
										<a-tree-select v-model:value="formState.materials[index].source_id" :show-search="true" placeholder="请选择材料名称" allow-clear tree-default-expand-all :tree-data="sourceOptions" tree-node-filter-prop="label" style="width:100%" @change="handleSourceChange(record)">
											<template #title="{ label }">{{ label }}</template>
										</a-tree-select>
									</a-form-item>
								</template>
								<template v-else-if="column.dataIndex === 'model'">
									<a-form-item :name="['materials', index, 'id']" :rules="{ required: true, message: '请选择规格' }">
										<a-select v-model:value="formState.materials[index].id" :show-search="true" placeholder="请选择" :options="modelOptions[record.source_id]" allow-clear :field-names="{ value: 'id', label: 'model' }" style="width:100%" @change="handleModelChange(record)"></a-select>
									</a-form-item>
								</template>
								<template v-else-if="column.dataIndex === 'unit'">
									<a-form-item :name="['materials', index, 'unit']" :rules="{ required: true, message: '请选择计量单位' }">
										<a-select v-model:value="formState.materials[index].unit" :show-search="true" placeholder="请选择" :options="unitOptions[record.id]" :field-names="{ value: 'name' }" style="width:100%"></a-select>
									</a-form-item>
								</template>
								<template v-else-if="column.dataIndex === 'quantity'">
									<a-form-item :name="['materials', index, 'quantity']" :rules="{ required: true, message: '请输入数量' }">
										<a-input-number v-model:value="formState.materials[index].quantity" placeholder="请输入数量" min="0" disabled @change="handleQuantityChange(record)" />
									</a-form-item>
								</template>
								<template v-else-if="column.dataIndex === 'use_time'">
									<a-form-item :name="['materials', index, 'use_time']" :rules="{ required: true, message: '请输入' }" @change="handleUseTimeChange(record)">
										<a-input-number v-model:value="formState.materials[index].use_time" placeholder="请输入" min="0" />
									</a-form-item>
								</template>
								<template v-else-if="column.dataIndex === 'time_unit'">
									<a-form-item :name="['materials', index, 'time_unit']" :rules="{ required: true, message: '请选择' }">
										<a-select v-model:value="formState.materials[index].time_unit" placeholder="请选择" :options="timeUnitOptions[record.id]" :field-names="{ value: 'name' }" style="width:100%"></a-select>
									</a-form-item>
								</template>
								<template v-else-if="column.dataIndex === 'use_date'">
									<a-form-item :name="['materials', index, 'use_date']" :rules="{ required: true, message: '请选择使用时间' }">
										<a-date-picker v-model:value="formState.materials[index].use_date" value-format="YYYY-MM-DD HH:mm:ss" show-time style="width:100%" />
									</a-form-item>
								</template>
								<template v-else-if="column.dataIndex === 'supplier_name'">
									<a-form-item :name="['materials', index, 'supplier_id']" :rules="{ required: true, message: '请选择供应商' }">
										<a-select v-model:value="formState.materials[index].supplier_id" :show-search="true" placeholder="请选择" :options="supplierOptions" allow-clear :field-names="{ value: 'id', label: 'company_name' }" style="width:100%" @change="handleSupplierChange(formState.materials[index])"></a-select>
									</a-form-item>
								</template>
								<template v-else-if="column.dataIndex === 'contract_id'">
									<a-form-item :name="['materials', index, 'contract_id']" :rules="{ required: true, message: '请选择合同' }">
										<a-select v-model:value="formState.materials[index].contract_id" :show-search="true" placeholder="请选择" :options="(contractByMaterialOptions[record.id] || []).filter(item => item.supplier_id === record.supplier_id)" :field-names="{ value: 'id', label: 'name' }" style="width:100%" allow-clear @change="handleContractChange(record)"></a-select>
									</a-form-item>
								</template>
								<template v-else-if="column.dataIndex === 'memo'">
									<a-form-item :name="['materials', index, 'memo']">
										<a-input v-model:value="formState.materials[index].memo" placeholder="请输入备注" />
									</a-form-item>
								</template>
								<template v-else-if="column.key === 'operation'">
									<a-space>
										<a-popconfirm title="确定要删除当前材料吗？" ok-text="是" cancel-text="否" @confirm="deleteMaterialModel(index)">
											<a-button type="link" style="color:#ff7875">
												<delete-outlined />删除
											</a-button>
										</a-popconfirm>
									</a-space>
								</template>
							</template>
						</a-table>
					</a-col>
					<a-col v-if="type === 'shangtong'">
						<a-table :pagination="false" :data-source="formState.materials" :columns="shangtongColumns.filter(item => !['contacts', 'tel', 'fangliang'].includes(item.dataIndex))" :row-key="(record) => record.key">
							<template #bodyCell="{ column, record, index }">
								<template v-if="column.dataIndex === 'id'">{{ index + 1 }}</template>
								<template v-else-if="column.dataIndex === 'part'">
									<!--									<a-form-item :name="['materials', index, 'part']" :rules="{ required: true, message: '请输入' }">-->
									<!--										<a-input v-model:value="formState.materials[index].part" placeholder="请输入" />-->
									<!--									</a-form-item>-->
									<!--									{{(applyPlanInfo.materials[0].gonghao?.name || '') + ((applyPlanInfo.materials[0].partInfo)?.name || '')}}-->
									{{ formState.materials[index].use_position }}
								</template>
								<template v-else-if="column.dataIndex === 'add_time'">
									<!--									<a-form-item :name="['materials', index, 'add_time']">-->
									<!--										<a-date-picker v-model:value="formState.materials[index].add_time" placeholder="请选择" value-format="YYYY-MM-DD HH:mm:ss" show-time style="width:100%" />-->
									<!--									</a-form-item>-->
									{{ formState.materials[index].add_time }}
								</template>
								<template v-else-if="column.dataIndex === 'model'">
									<!--									<a-form-item :name="['materials', index, 'id']" :rules="{ required: true, message: '请选择规格' }">-->
									<!--										<a-select v-model:value="formState.materials[index].id" :show-search="true" placeholder="请选择" :options="modelOptions" allow-clear :field-names="{ value: 'id', label: 'model' }" style="width:100%"></a-select>-->
									<!--									</a-form-item>-->
									{{ formState.materials[index].material_name }}
								</template>
								<template v-else-if="column.dataIndex === 'cg_fangliang'">
									<a-form-item :name="['materials', index, 'cg_fangliang']" :rules="{ required: true, message: '请输入' }">
										<a-input-number v-model:value="formState.materials[index].cg_fangliang" placeholder="请输入" min="0" @change="changeCGFangliang(formState.materials[index].cg_fangliang, formState.materials[index])" />
									</a-form-item>
								</template>
								<template v-else-if="column.dataIndex === 'changdu'">
									<!--									<a-form-item :name="['materials', index, 'changdu']" :rules="{ required: true, message: '请输入' }">-->
									<!--										<a-input v-model:value="formState.materials[index].changdu" placeholder="请输入" />-->
									<!--									</a-form-item>-->
									{{ formState.materials[index].changdu }}
								</template>
								<template v-else-if="column.dataIndex === 'luodu'">
									<!--									<a-form-item :name="['materials', index, 'luodu']" :rules="{ required: true, message: '请输入' }">-->
									<!--										<a-input v-model:value="formState.materials[index].luodu" placeholder="请输入" />-->
									<!--									</a-form-item>-->
									{{ formState.materials[index].luodu }}
								</template>
								<template v-else-if="column.dataIndex === 'supplier_name'">
									<a-form-item :name="['materials', index, 'supplier_id']" :rules="{ required: true, message: '请选择供应商' }">
										<a-select v-model:value="formState.materials[index].supplier_id" :show-search="true" placeholder="请选择" :options="supplierByMaterialOptions[record.id]" allow-clear :field-names="{ value: 'id', label: 'company_name' }" style="width:100%" @change="handleSupplierChange(formState.materials[index])"></a-select>
									</a-form-item>
								</template>
								<template v-else-if="column.dataIndex === 'contract_id'">
									<a-form-item :name="['materials', index, 'contract_id']" :rules="{ required: true, message: '请选择合同' }">
										<a-select v-model:value="formState.materials[index].contract_id" :show-search="true" placeholder="请选择" :options="(contractByMaterialOptions[record.id] || []).filter(item => item.supplier_id === record.supplier_id).map(({id, name}) => ({id: id.toString(), name}))" :field-names="{ value: 'id', label: 'name' }" style="width:100%" allow-clear @change="handleContractChange(record)"></a-select>
									</a-form-item>
								</template>
								<template v-else-if="column.dataIndex === 'art_indexes'">
									<a-form-item :name="['materials', index, 'art_gonghao_ids']">
										<a-select v-model:value="formState.materials[index].art_gonghao_ids" mode="multiple" :show-search="true" placeholder="请选择技术指标" :options="artIndexesMap[formState.materials[index].contract_id]" :disabled="!formState.materials[index].contract_id" allow-clear></a-select>
									</a-form-item>
								</template>
								<template v-else-if="column.dataIndex === 'memo'">
									<a-form-item :name="['materials', index, 'memo']">
										<!--										<a-input v-model:value="formState.materials[index].memo" placeholder="请输入备注" />-->
										{{ formState.materials[index].memo }}
									</a-form-item>
								</template>
							</template>
						</a-table>
					</a-col>
					<a-col v-if="type === 'auxiliary'">
						<a-table :pagination="false" :data-source="formState.materials" :columns="auxiliaryColumns" :row-key="(record) => record.key">
							<template #bodyCell="{ column, record, index }">
								<template v-if="column.dataIndex === 'id'">{{ index + 1 }}</template>
								<template v-if="column.dataIndex === 'name'">
									<a-form-item :name="['materials', index, 'source_id']" :rules="{ required: true, message: '请选择材料名称' }">
										<a-tree-select v-model:value="formState.materials[index].source_id" :show-search="true" placeholder="请选择材料名称" allow-clear tree-default-expand-all :tree-data="sourceOptions" tree-node-filter-prop="label" style="width:100%" @change="handleSourceChange(record)">
											<template #title="{ label }">{{ label }}</template>
										</a-tree-select>
									</a-form-item>
								</template>
								<template v-else-if="column.dataIndex === 'model'">
									<a-form-item :name="['materials', index, 'id']" :rules="{ required: true, message: '请选择规格' }">
										<a-select v-model:value="formState.materials[index].id" :show-search="true" placeholder="请选择" :options="modelOptions[record.source_id]" allow-clear :field-names="{ value: 'id', label: 'model' }" style="width:100%" @change="handleModelChange(record)"></a-select>
									</a-form-item>
								</template>
								<template v-else-if="column.dataIndex === 'unit'">
									<a-form-item :name="['materials', index, 'unit']" :rules="{ required: true, message: '请选择计量单位' }">
										<a-select v-model:value="formState.materials[index].unit" :show-search="true" placeholder="请选择" :options="unitOptions[record.id]" :field-names="{ value: 'name' }" style="width:100%"></a-select>
									</a-form-item>
								</template>
								<template v-else-if="column.dataIndex === 'quantity'">
									<a-form-item :name="['materials', index, 'quantity']" :rules="{ required: true, message: '请输入数量' }">
										<a-input-number v-model:value="formState.materials[index].quantity" placeholder="请输入数量" min="0" @change="handleQuantityChange(record)" />
									</a-form-item>
								</template>
								<template v-else-if="column.dataIndex === 'supplier_name'">
									<a-form-item :name="['materials', index, 'supplier_id']" :rules="{ required: true, message: '请选择供应商' }">
										<a-select v-model:value="formState.materials[index].supplier_id" :show-search="true" placeholder="请选择" :options="supplierOptions" allow-clear :field-names="{ value: 'id', label: 'company_name' }" style="width:100%" @change="handleSupplierChange(formState.materials[index])"></a-select>
									</a-form-item>
								</template>
								<template v-else-if="column.dataIndex === 'contract_id'">
									<a-form-item :name="['materials', index, 'contract_id']" :rules="{ required: true, message: '请选择合同' }">
										<a-select v-model:value="formState.materials[index].contract_id" :show-search="true" placeholder="请选择" :options="(contractBySupplierOptions[record.supplier_id] || []).filter(item => item.supplier_id === record.supplier_id)" :field-names="{ value: 'id', label: 'name' }" style="width:100%" allow-clear @change="handleContractChange(record)"></a-select>
									</a-form-item>
								</template>
								<template v-else-if="column.dataIndex === 'memo'">
									<a-form-item :name="['materials', index, 'memo']">
										<a-input v-model:value="formState.materials[index].memo" placeholder="请输入备注" />
									</a-form-item>
								</template>
								<template v-else-if="column.key === 'operation'">
									<a-space>
										<a-popconfirm title="确定要删除当前材料吗？" ok-text="是" cancel-text="否" @confirm="deleteMaterialModel(index)">
											<a-button type="link" style="color:#ff7875">
												<delete-outlined />删除
											</a-button>
										</a-popconfirm>
									</a-space>
								</template>
							</template>
						</a-table>
					</a-col>
				</a-col>

				<!-- <a-col :span="24" style="margin-top: 24px;">
					<a-form-item class="flex-auto" label="备注" name="memo">
						<a-textarea v-model:value="formState.memo" :auto-size="{minRows:4, maxRows:6}"></a-textarea>
					</a-form-item>
				</a-col>-->

				<a-row :gutter="20">
					<a-col :span="24" class="py-4 text-center">
						<a-space>
							<a-button type="primary" html-type="submit" :loading="submitLoading">
								<save-outlined />提交采购申请
							</a-button>
							<a-button @click="closeTab('/purchaseManage')">
								<close-outlined />关闭
							</a-button>
						</a-space>
					</a-col>
				</a-row>
			</a-form>
		</template>
	</div>
</template>

<script setup>
import { ref, computed, onMounted, getCurrentInstance, inject } from "vue";
import { Modal } from "ant-design-vue";
import { ReloadOutlined, DeleteOutlined, SaveOutlined, CloseOutlined, PlusOutlined, EditOutlined } from "@ant-design/icons-vue";
import { post, postJson } from "../utils";
import { useRoute, useRouter } from "vue-router";
import { add, subtract } from '../utils/operation.js'
import dayjs from "dayjs";
const route = useRoute();
const router = useRouter();
const id = computed(() => {
	return route.params.id || 0;
});

const showCreateForm = ref(false);
const formState = ref({ materials: [] });
const userlist = ref([]);
const formRef = ref();
const { proxy } = getCurrentInstance();
const submitLoading = ref(false);
const showAddBtn = ref(true);
const artIndexesGongHaos = ref([]);
const artIndexesMap = ref({});
post("dictionary", { root_id: 1069 }).then((data) => {
	artIndexesGongHaos.value = data.map(d => {
		return {
			value: d.id,
			label: d.name
		};
	});
});
const addMaterialModel = () => {
	if (type.value === "shangtong") {
		const listInfo = applyPlanInfo.value.materials[0];
		if (!listInfo.material) listInfo.material = {};

		formState.value.materials.push({
			id: listInfo.material.id,
			gonghao_id: listInfo.gonghao_id,
			position: listInfo.part,
			use_position: (listInfo.gonghao?.name || "") + (listInfo.partInfo?.name || ""),
			material_name: (listInfo.material?.name || "") + (listInfo.material?.model || ""),
			add_time: listInfo.add_time,
			changdu: listInfo.changdu,
			luodu: listInfo.luodu,
			model: listInfo.model,
			memo: listInfo.memo,
			expected_location: listInfo.expected_location
		});
	} else {
		formState.value.materials.push({});
	}
	showAddBtn.value = type.value !== "shangtong";
};

const purchaseColumns = [
	{
		title: "序号",
		dataIndex: "id",
		width: 60,
		align: "center"
	},
	{
		title: "物资名称",
		dataIndex: "name",
		ellipsis: true,
	},
	{
		title: "型号规格",
		dataIndex: "model",
		ellipsis: true
	},
	{
		title: "单位",
		dataIndex: "unit",
		align: "center"
	},
	{
		title: "供应商",
		dataIndex: "supplier_name",
		align: "center"
	},
	{
		title: "合同",
		dataIndex: "contract_id",
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return record.PurchaseOrderMaterial?.contract?.name;
		}
	},
	{
		title: "申请数量",
		dataIndex: "quantity",
		align: "center"
	},
	{
		title: "已采购数量",
		dataIndex: "purchaseCount",
		align: "center"
	},
	{
		title: "已发货数量",
		dataIndex: "shipped",
		align: "center"
	},
	{
		title: "本次申请未采购余量",
		dataIndex: "currentRemainder",
		align: "center"
	},
	{
		title: "合同余量",
		dataIndex: "pendingQuantity",
		align: "center"
	},
	{
		title: "备注",
		dataIndex: "memo",
		align: "center"
	},
	{
		title: "操作",
		key: "operation",
		sorter: false,
		fixed: "right",
		width: 80,
		align: "center"
	}
];

const shangtongColumns = [
	{
		title: "工号",
		dataIndex: "part",
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return (record.gonghao?.name || "") + (record.partInfo?.name || "");
		}
	},
	{
		title: "预计浇筑部位",
		dataIndex: "expected_location",
		ellipsis: true
	},
	{
		title: "砼标号（类别）",
		dataIndex: "model",
		customRender: ({ text, record, index, column }) => {
			return (record.material?.name || "") + (record.material?.model || "");
		}
	},
	{
		title: "预计浇筑方量（m3）",
		dataIndex: "fangliang",
		align: "center"
	},
	{
		title: "是否泵送（长度）",
		dataIndex: "changdu",
		align: "center"
	},
	{
		title: "申请塌落度（mm）",
		dataIndex: "luodu",
		align: "center"
	},
	{
		title: "现场联系人",
		dataIndex: "contacts",
		align: "center"
	},
	{
		title: "现场联系电话",
		dataIndex: "tel",
		align: "center"
	},
	{
		title: "预计浇筑日期",
		dataIndex: "add_time",
		align: "center"
	},
	{
		title: "供应商",
		dataIndex: "supplier_name",
		align: "center"
	},
	{
		title: "合同",
		dataIndex: "contract_id",
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return record.PurchaseOrderMaterial?.contract?.name;
		}
	},
	{
		title: "技术指标",
		dataIndex: "art_indexes",
		align: "center",
		width: 200,
	},
	{
		title: "采购方量（m3）",
		dataIndex: "cg_fangliang",
		align: "center"
	},
	{
		title: "合同余量",
		dataIndex: "pendingQuantity",
		align: "center"
	},
	{
		title: "备注",
		dataIndex: "memo",
		align: "center"
	}
];

const machineapplyColumns = [
	{
		title: "序号",
		dataIndex: "id",
		width: 60,
		align: "center"
	},
	{
		title: "机械名称",
		dataIndex: "name",
		ellipsis: true
	},
	{
		title: "规格型号",
		dataIndex: "model",
		align: "center",
		width: 150
	},
	{
		title: "计量单位",
		dataIndex: "unit",
		align: "center"
	},
	{
		title: "供应商",
		dataIndex: "supplier_name",
		align: "center"
	},
	{
		title: "合同",
		dataIndex: "contract_id",
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return record.PurchaseOrderMaterial?.contract?.name;
		}
	},
	{
		title: "数量",
		dataIndex: "quantity",
		align: "center"
	},
	{
		title: "使用时长",
		dataIndex: "use_time",
		align: "center"
	},
	// {
	// 	title: "时长单位",
	// 	dataIndex: "time_unit",
	// 	align: "center"
	// },
	{
		title: "使用时间",
		dataIndex: "use_date",
		align: "center",
		width: 190,
		customRender: ({ text, record, index, column }) => {
			return text ? dayjs(text).format("YYYY-MM-DD HH:mm:ss") : "";
		}
	},
	{
		title: "本次申请未采购余量",
		dataIndex: "currentRemainder",
		align: "center"
	},
	{
		title: "合同余量",
		dataIndex: "pendingQuantity",
		align: "center"
	},
	{
		title: "备注",
		dataIndex: "memo",
		align: "center"
	},
	{
		title: "操作",
		key: "operation",
		sorter: false,
		fixed: "right",
		width: 80,
		align: "center"
	}
];

const auxiliaryColumns = [
	{
		title: "序号",
		dataIndex: "id",
		width: 60,
		align: "center"
	},
	{
		title: "物料名称",
		dataIndex: "name",
		ellipsis: true
	},
	{
		title: "规格型号",
		dataIndex: "model",
		align: "center",
		width: 150
	},
	{
		title: "计量单位",
		dataIndex: "unit",
		align: "center"
	},
	{
		title: "供应商",
		dataIndex: "supplier_name",
		align: "center"
	},
	{
		title: "合同",
		dataIndex: "contract_id",
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return contractInfos.value.find(item => item.id === parseInt(text))?.name;
		}
	},
	{
		title: "申请数量",
		dataIndex: "quantity",
		align: "center"
	},
	{
		title: "已采购数量",
		dataIndex: "purchaseCount",
		align: "center"
	},
	{
		title: "已发货数量",
		dataIndex: "shipped",
		align: "center"
	},
	{
		title: "本次申请未采购余量",
		dataIndex: "currentRemainder",
		align: "center"
	},
	{
		title: "备注",
		dataIndex: "memo",
		align: "center"
	},
	{
		title: "操作",
		key: "operation",
		sorter: false,
		fixed: "right",
		width: 80,
		align: "center"
	}
];

const purchaseHistoryColumns = [
	{
		title: "采购日期",
		dataIndex: "create_time",
		customRender: ({ text, record, index, column }) => {
			return dayjs(text).format("YYYY-MM-DD HH:mm:ss");
		}
	},
	{
		title: "采购单编号",
		dataIndex: "code",
		ellipsis: true
	},
	{
		title: "采购人",
		dataIndex: "purchaser",
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return text.fullname || text.username;
		}
	},
	{
		title: "送达地址",
		dataIndex: "deliver_address",
		align: "center"
	},
	{
		title: "送达时间",
		dataIndex: "deliver_time",
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return (text && dayjs(text).format("YYYY-MM-DD HH:mm:ss")) || "";
		}
	},
	{
		title: "现场联系人",
		dataIndex: "receiver",
		align: "center"
	},
	{
		title: "联系电话",
		dataIndex: "receiver_tel",
		align: "center"
	},
	{
		title: "操作",
		key: "operation",
		sorter: false,
		fixed: "right",
		width: 180,
		align: "center"
	}
];

const sourceOptions = ref([]);
const modelOptions = ref({});
const unitOptions = ref({});
const timeUnitOptions = ref({});
// 物资信息
const materialInfo = ref({});
const purchasedMaterialInfo = ref({});
const supplierOptions = ref([]);
const supplierByMaterialOptions = ref([]);
const contractByMaterialOptions = ref({});
const contractBySupplierOptions = ref({});
const applyPlanInfo = ref({});
const type = computed(() => route.query.type);
const purchasedOrderList = ref([]);
const contractInfos = ref([]);

const innerColumns = computed(() => {
	if (type.value === "purchase") {
		return purchaseColumns.filter(item => item.dataIndex !== "id" && item.key !== "operation" && item.dataIndex !== "purchaseCount" && item.dataIndex !== "currentRemainder" && item.dataIndex !== "pendingQuantity");
	} else if (type.value === "shangtong") {
		return shangtongColumns.filter(item => !["contacts", "tel", "fangliang", "pendingQuantity", "currentRemainder"].includes(item.dataIndex));
	} else if (type.value === "machineapply") {
		return machineapplyColumns.filter(item => !["pendingQuantity", "currentRemainder"].includes(item.dataIndex));
	} else if (type.value === "auxiliary") {
		return auxiliaryColumns.filter(item => !["pendingQuantity", "currentRemainder", "purchaseCount"].includes(item.dataIndex));
	} else {
		return machineapplyColumns.filter(item => !["pendingQuantity", "currentRemainder"].includes(item.dataIndex));
	}
});

const handleAdd = () => {
	if (type.value === "shangtong") {
		formState.value.deliver_address = "";
		formState.value.deliver_time = null;
		if (!applyPlanInfo.value.contacts_id) {
			formState.value.receiver_id = userlist.value.find(item => item.label === applyPlanInfo.value.contacts)?.value;
		} else {
			formState.value.receiver_id = applyPlanInfo.value.contacts_id;
		}
		formState.value.receiver = applyPlanInfo.value.contacts || "";
		formState.value.receiver_tel = applyPlanInfo.value.tel || "";
	} else {
		formState.value.deliver_address = applyPlanInfo.value.deliver_address || "";
		//formState.value.deliver_time = applyPlanInfo.value.deliver_time && dayjs(applyPlanInfo.value.deliver_time);
		formState.value.deliver_time = null;
		if (!applyPlanInfo.value.receiver_id) {
			formState.value.receiver_id = userlist.value.find(item => item.label === applyPlanInfo.value.receiver)?.value;
		} else {
			formState.value.receiver_id = applyPlanInfo.value.receiver_id || "";
		}
		formState.value.receiver = applyPlanInfo.value.receiver || "";
		formState.value.receiver_tel = applyPlanInfo.value.receiver_tel || "";
	}
	if (formState.value.receiver_id) {
		changeUser(formState.value.receiver_id);
	}
	formState.value.materials = [];
	showCreateForm.value = true;
	showAddBtn.value = true;
	currentEditItemId.value = "";
};

const currentEditItemId = ref("");
const handleEdit = record => {
	if (showCreateForm.value === true) {
		proxy.$message.error("当前有正在操作的数据，请先完成后再执行该操作");
		return;
	}
	currentEditItemId.value = record.id;
	if (type.value === "shangtong") {
		const listInfo = applyPlanInfo.value.materials[0];
		Object.assign(record.materials[0], {
			use_position: (listInfo.gonghao?.name || "") + (listInfo.partInfo?.name || ""),
			material_name: (listInfo.material?.name || "") + (listInfo.material?.model || ""),
			cg_fangliang: record.materials[0].fangliang,
			gonghao_id: listInfo.gonghao_id,
			position: listInfo.part,
			memo: listInfo.memo
		});
	}

	formState.value.materials = (record.materials || []).concat();
	//计算合同余量
	formState.value.materials.forEach(item => {
		handleContractChange(item);
	});

	formState.value.deliver_address = record.deliver_address || "";
	formState.value.deliver_time = record.deliver_time || "";
	formState.value.receiver = record.receiver || "";
	formState.value.receiver_tel = record.receiver_tel || "";
	showCreateForm.value = true;
	showAddBtn.value = type.value !== "shangtong";
	if (!applyPlanInfo.value.receiver_id) {
		formState.value.receiver_id = userlist.value.find(item => item.label === applyPlanInfo.value.receiver)?.value;
	} else {
		formState.value.receiver_id = applyPlanInfo.value.receiver_id || "";
	}
	if (formState.value.receiver_id) {
		changeUser(formState.value.receiver_id);
	}
};

const handleCancelEdit = () => {
	formState.value = {};
	showCreateForm.value = false;
	currentEditItemId.value = "";
};

const handleDel = (id, index) => {
	Modal.confirm({
		title: "操作确认?",
		content: "您确定要删除当前采购记录吗",
		onOk() {
			post("purchaseOrder/delete", { id })
				.then(() => {
					proxy.$message.success("删除成功", 1);
					purchasedOrderList.value.splice(index, 1);
					setTimeout(() => {
						router.go(0);
					}, 500)
					
				})
				.catch(err => {
					proxy.$message.error(err);
				});
		}
	});
};

onMounted(() => {
	post(`${type.value}/info`, { id: route.query.planId }).then(data => {
		let types = [];
		let material_types = [];
		switch (type.value) {
		case 'purchase':
			types = [1, 2];
			material_types = [1, 3];
			break;
		case 'shangtong':
			types = [1];
			material_types = [2];
			break;
		case 'machineapply':
			types = [3];
			break;
		case 'auxiliary':
			types = [4];
			break;
		}
		// get supplier options by contracts
		postJson("contract/apply", { project_id: data.project_id, types, material_types }).then(data => {
			contractInfos.value = data;
			const contractInfos2Materials = {};
			const contractInfos2Suppliers = {};
			const supplierInfos2Materials = {};
			for (const d of data) {
				if (type.value !== "auxiliary") {
					for (const material of d.materials) {
						if (!supplierInfos2Materials[material.id]) {
							supplierInfos2Materials[material.id] = [];
						}
						if (!contractInfos2Materials[material.id]) {
							contractInfos2Materials[material.id] = [];
						}
						const supplierIds = supplierInfos2Materials[material.id].map(item => item.id);
						if (!supplierIds.includes(d.supplier_id)) {
							supplierInfos2Materials[material.id].push({
								id: d.supplier_id,
								company_name: d.supplier?.company_name || ""
							});
						}
						contractInfos2Materials[material.id].push({
							id: d.id,
							name: d.name,
							supplier_id: d.supplier_id
						});
					}
				} else {
					if (!contractInfos2Suppliers[d.supplier_id]) contractInfos2Suppliers[d.supplier_id] = [];
					contractInfos2Suppliers[d.supplier_id].push({
						id: d.id,
						name: d.name,
						supplier_id: d.supplier_id
					});
				}
			}
			contractByMaterialOptions.value = contractInfos2Materials;
			supplierByMaterialOptions.value = supplierInfos2Materials;
			const suppliers = data.map(item => item.supplier).filter(item => !!item);
			supplierOptions.value = suppliers.reduce((res, curr) => {
				const supplierIds = res.map(item => item.id);
				if (!supplierIds.includes(curr.id)) {
					res.push(curr);
				}
				return res;
			}, []);
			if (type.value === "auxiliary") {
				contractBySupplierOptions.value = contractInfos2Suppliers;
			}
		});
		post("project/user", { project_id: data.project_id, scene: "main", status: "1" }).then(data => {
			userlist.value = data.map(d => ({
				label: d.fullname || d.username,
				value: d.id,
				mobile: d.mobile
			}));
		});
		applyPlanInfo.value = data;
		if (data.art_indexes) {
			applyPlanInfo.value.art_indexes = JSON.parse(data.art_indexes) || [];
		}
		applyPlanInfo.value.applier = data.applier || data.purchaser;
		applyPlanInfo.value.deliver_time = data.deliver_time && dayjs(data.deliver_time).format("YYYY-MM-DD HH:mm:ss");
		applyPlanInfo.value.create_time = dayjs(data.create_time).format("YYYY-MM-DD HH:mm:ss");

		if (type.value === "shangtong") {
			data.materials = [
				{
					...applyPlanInfo.value,
					add_time: dayjs(applyPlanInfo.value.add_time).format("YYYY-MM-DD HH:mm:ss"),
					model: applyPlanInfo.value.type
				}
			];
			modelOptions.value = [
				{
					id: applyPlanInfo.value.material_id,
					model: applyPlanInfo.value.type
				}
			];

		} else {
			const materialEntityKey = type.value.charAt(0).toUpperCase() + type.value.slice(1) + "Material";
			// 物资唯一 按照物资分组统计
			materialInfo.value = data.materials.reduce((res, curr) => {
				if (!res[curr.id]) {
					const model = curr.attr ? `${curr.model}（${curr.attr}）` : curr.model;
					res[curr.id] = {
						name: curr.name,
						model: model, // 型号
						unit: curr[materialEntityKey].unit, // 单位
						time_unit: curr[materialEntityKey].time_unit,
						source_id: curr.source_id, // 字典物料id
						quantity: 0, // 当前物资数量
						use_time: 0,
					};
				}

				// 物资数量汇总
				const quantity = Number(curr[materialEntityKey].quantity);
				res[curr.id].quantity += isNaN(quantity) ? 0 : quantity;
				if (type.value === "machineapply") {
					res[curr.id].use_time = add([res[curr.id].use_time, curr[materialEntityKey].use_time]);
				}
				return res;
			}, {});

			sourceOptions.value = Object.keys(materialInfo.value)
				.map(materialId => {
					return {
						value: materialInfo.value[materialId].source_id,
						label: materialInfo.value[materialId].name
					};
				})
				.reduce((res, curr) => {
					const ids = res.map(item => item.value);
					if (!ids.includes(curr.value)) {
						res.push(curr);
					}
					return res;
				}, []);
			const sourceIds = sourceOptions.value.map(item => item.value);
			modelOptions.value = sourceIds.reduce((res, sourceId) => {
				const materialIds = Object.keys(materialInfo.value).filter(materialId => materialInfo.value[materialId].source_id === sourceId);
				res[sourceId] = materialIds.map(materialId => {
					return {
						id: Number(materialId),
						model: materialInfo.value[materialId].model
					};
				});
				return res;
			}, {});

			unitOptions.value = Object.keys(materialInfo.value).reduce((res, materialId) => {
				res[materialId] = [
					{
						name: materialInfo.value[materialId].unit,
						label: materialInfo.value[materialId].unit
					}
				];
				return res;
			}, {});

			timeUnitOptions.value = Object.keys(materialInfo.value).reduce((res, materialId) => {
				res[materialId] = [
					{
						name: materialInfo.value[materialId].time_unit,
						label: materialInfo.value[materialId].time_unit
					}
				];
				return res;
			}, {});

			// for display info
			data.materials = data.materials.map(item => {
				const { unit, quantity, memo, use_date, use_time, time_unit } = item[materialEntityKey];
				return {
					...item,
					unit,
					quantity,
					memo,
					use_date,
					use_time,
					time_unit
				};
			});
		}

		// 采购记录 当前已采购物资
		post(`purchaseOrder/all`, { apply_plan_id: route.query.planId, type: type.value }).then(data => {
			purchasedOrderList.value = data.map(item => {
				item.materials = (item.materials || []).map(item => {
					const { quantity, supplier_id, unit, memo, use_date, use_time, time_unit, fangliang, luodu, changdu, add_time, supplier_name, part, contract_id, expected_location } = item.PurchaseOrderMaterial;
					let art_indexes = item.PurchaseOrderMaterial.art_indexes;
					if (type.value === 'shangtong' && art_indexes) {
						art_indexes = JSON.parse(art_indexes);
					}
					return {
						...item,
						quantity,
						unit,
						memo,
						use_date: use_date ? dayjs(use_date).format("YYYY-MM-DD HH:mm:ss") : null,
						use_time,
						time_unit,
						supplier_id,
						supplier_name,
						fangliang,
						luodu,
						changdu,
						part,
						contract_id,
						expected_location,
						shipped: item.real_quantity,
						add_time: dayjs(add_time).format("YYYY-MM-DD HH:mm:ss"),
						art_indexes
					};
				});
				return item;
			});
			// 物资唯一 按照物资分组统计
			const materials = data
				.map(item => item.materials)
				.reduce((res, curr) => {
					res.push(...curr);
					return res;
				}, []);
			purchasedMaterialInfo.value = materials.reduce((res, curr) => {
				if (!res[curr.id]) {
					res[curr.id] = {
						quantity: 0, // 当前物资数量
						shipped: 0, // 当前已发货数量
						source_id: curr.source_id,
						use_time: 0,
					};
				}
				// 物资数量汇总
				const quantity = Number(curr.PurchaseOrderMaterial.quantity || curr.PurchaseOrderMaterial.fangliang);
				res[curr.id].quantity += isNaN(quantity) ? 0 : quantity;
				res[curr.id].shipped += isNaN(Number(curr.shipped)) ? 0 : Number(curr.shipped);
				if (type.value === 'machineapply') {
					res[curr.id].use_time = add([res[curr.id].use_time, curr.PurchaseOrderMaterial.use_time])
				}
				return res;
			}, {});
			//purchaseCount
			applyPlanInfo.value.materials?.forEach(item => {
				item.purchaseCount = purchasedMaterialInfo.value[item.id]?.quantity || 0;
				item.shipped = purchasedMaterialInfo.value[item.id]?.shipped || 0;
				if (type.value === 'machineapply') {
					item.currentRemainder = subtract([item.use_time, purchasedMaterialInfo.value[item.id]?.use_time]);
				} else {
					item.currentRemainder = (item.quantity * 10000 - item.purchaseCount * 10000) / 10000;
				}
			});

		});
	});
});
const changeUser = userId => {
	const user = userlist.value.find(d => d.value === userId);
	formState.value.receiver = user.label;
	formState.value.receiver_tel = user.mobile;
};

const handleSourceChange = record => {
	record.id = undefined;
	record.unit = undefined;
};

const handleModelChange = record => {
	record.unit = undefined;

	// 计算剩余采购数量
	if (type.value === "purchase") {
		// 物料历史汇总
		// const materialSum = Object.values(purchasedMaterialInfo.value).filter(item => item.id === record.id)[0] || {};
		const materialSum = purchasedMaterialInfo.value[record.id] || {};
		// 采购订单详情物料汇总
		const purchaseOrderMaterial = applyPlanInfo.value.materials.filter(item => item.id === record.id)[0] || {};

		record.purchaseCount = materialSum.quantity || 0;
		record.shipped = materialSum.shipped || 0;
		record.currentRemainder = (purchaseOrderMaterial.quantity * 10000 - record.purchaseCount * 10000) / 10000;
	} else if (type.value === "machineapply") {
		// 采购订单详情物料汇总
		const purchaseOrderMaterial = applyPlanInfo.value.materials.filter(item => item.id === record.id)[0] || {};
		const materialSum = purchasedMaterialInfo.value[record.id] || {};
		record.purchaseCount = materialSum.quantity || 0;
		record.currentRemainder = subtract([purchaseOrderMaterial.use_time, materialSum.use_time]);
	} else if (type.value === "auxiliary") {
		const purchaseOrderMaterial = applyPlanInfo.value.materials.filter(item => item.id === record.id)[0] || {};
		const materialSum = purchasedMaterialInfo.value[record.id] || {};
		record.purchaseCount = materialSum.quantity || 0;
		record.currentRemainder = (purchaseOrderMaterial.quantity * 10000 - record.purchaseCount * 10000) / 10000;
		record.shipped = materialSum.shipped || 0;
	}
};
const handleUnitChange = record => {
	if (record.id) {
		const materialIds = formState.value.materials.filter(item => item.id === record.id);
		if (materialIds.length > 1) {
			proxy.$message.error("请勿选择相同的物料");
			record.id = null;
			record.unit = null;
		}
	}
	record.contract_id = null;
	record.supplier_name = null;
	record.supplier_id = null;
};
const handleSupplierChange = obj => {
	const supplier_name = supplierOptions.value.find(item => item.id === obj.supplier_id).company_name;
	obj.supplier_name = supplier_name;
	obj.contract_id = null;
	obj.pendingQuantity = null;
};

// 合同改变
const handleContractChange = async record => {
	if (record.contract_id) {
		// 查询合同关联采购订单物料
		const contractionInfo = contractInfos.value.filter(item => item.id === parseInt(record.contract_id))[0];
		const material = contractionInfo.materials.filter(item => item.id === record.id)[0];
		record.pendingQuantity = material?.ContractMaterial?.pending_quantity;
		record.contractUseTime = material?.ContractMaterial.use_time || 0;
		record.use_time = null;
		if (type.value === "machineapply") {
			record.quantity = 1;
		} else {
			if (type.value === "shangtong") {
				let allowQuantity = applyPlanInfo.value.materials.filter(item => item.material_id === record.id)[0]?.fangliang;
				allowQuantity = subtract([allowQuantity, purchasedMaterialInfo.value[record.id]?.quantity || 0]);
				allowQuantity = allowQuantity > record.pendingQuantity ? record.pendingQuantity : allowQuantity;
				record.fangliang = allowQuantity;
				record.cg_fangliang = allowQuantity;
			} else {
				record.quantity = record.currentRemainder > record.pendingQuantity ? record.pendingQuantity : record.currentRemainder;
			}
		}

		if (record.pendingQuantity < 0) {
			record.pendingQuantity = 0;
		}
		if (!contractionInfo.art_indexes || artIndexesMap.value[record.contract_id] || type.value !== 'shangtong') return;
		// 获取合同技术指标
		artIndexesMap.value[record.contract_id] = JSON.parse(contractionInfo.art_indexes).map(item => {
			return {
				value: item.gonghao_id,
				label: artIndexesGongHaos.value.find(i => i.value === item.gonghao_id)?.label,
				price: item.price,
			}
		});
	}
};

// 申请数量改变
const handleQuantityChange = record => {
	const allowQuantity = record.currentRemainder > record.pendingQuantity ? record.pendingQuantity : record.currentRemainder;
	if (record.quantity > allowQuantity && type.value !== "auxiliary") {
		proxy.$message.error("申请数量不能大于合同余量或本次申请未采购余量");
		record.quantity = allowQuantity;
	}
	if (parseFloat(record.quantity) === 0) {
		record.quantity = null;
	}
};
// 使用时长改变
const handleUseTimeChange = record => {
	if (!record.id) return;
	if (record.unit === "小时") {
		if (record.use_time > 20) {
			proxy.$message.error("单位为小时物料单次使用时长不能超过20小时");
			record.use_time = 20;
		}
	}
	// const purchaseUseTime = applyPlanInfo.value.materials.filter(item => parseInt(item.id) === parseInt(record.id))[0]?.use_time;
	// const maxAllowUseTime = record.contractUseTime < (purchaseUseTime || 0) ? record.contractUseTime : purchaseUseTime || 0;
	// if (record.use_time > maxAllowUseTime) {
	// 	proxy.$message.error("使用时长不能大于合同或申请使用时长");
	// 	record.use_time = maxAllowUseTime;
	// }
	// if (parseInt(record.use_time) === 0) {
	// 	record.use_time = null;
	// }
};

const handleSave = () => {
	formRef.value
		.validate()
		.then(() => {
			proxy.$message.destroy();
			const params = { ...formState.value };

			if (!params.materials.length) {
				proxy.$message.error("请添加材料清单");
				return;
			}

			if (type.value !== "shangtong") {
				// 判断所有物资不能超过计划
				const sourceIds = params.materials.map(item => item.source_id);
				const targetSourceIds = Object.keys(materialInfo.value).map(materialId => materialInfo.value[materialId].source_id);
				if (sourceIds.some(sourceId => !targetSourceIds.includes(sourceId))) {
					proxy.$message.error("只能选择计划内的物资");
					return;
				}
				// 2. 判断物资数量
				const summaryRes = params.materials.reduce((res, curr) => {
					if (!res[curr.id]) {
						res[curr.id] = {
							quantity: 0
						};
					}
					res[curr.id].quantity += Number(curr.quantity);
					return res;
				}, {});
				const isValid = Object.keys(summaryRes).every(materialId => {
					return summaryRes[materialId].quantity <= materialInfo.value[materialId].quantity;
				});
				if (!isValid) {
					proxy.$message.error("物资数量不能超过计划数量");
					return;
				}
				if (type.value === 'machineapply') {
					const summaryUseTime = params.materials.reduce((res, curr) => {
						if (!res[curr.id]) {
							res[curr.id] = {
								use_time: 0
							};
						}
						res[curr.id].use_time = add([res[curr.id].use_time, curr.use_time]);
						return res;
					}, {});
					const isValid2 = Object.keys(summaryUseTime).every(materialId => {
						return summaryUseTime[materialId].use_time <= (materialInfo.value[materialId].use_time - (purchasedMaterialInfo.value[materialId]?.use_time || 0));
					});
					if (!isValid2) {
						proxy.$message.error("物资数量不能超过剩余可采购数量");
						return;
					}
				} else {
					const isValid2 = Object.keys(summaryRes).every(materialId => {
						return summaryRes[materialId].quantity <= materialInfo.value[materialId].quantity - ((purchasedMaterialInfo.value[materialId] && purchasedMaterialInfo.value[materialId].quantity) || 0);
					});
					if (!isValid2) {
						proxy.$message.error("物资数量不能超过剩余可采购数量");
						return;
					}
				}

				params.materials = JSON.stringify(params.materials);
			} else {
				// 商砼 只有一条数据
				if (!applyPlanInfo.value.material_id) {
					proxy.$message.error("当前商砼预约计划缺少物资ID");
					return;
				}

				const summaryQuantity = params.materials.reduce((res, curr) => {
					res += Number(curr.fangliang);
					return res;
				}, 0);
				const applyPlanQuantity = Number(applyPlanInfo.value.fangliang);
				const purchasedQuantity = (purchasedMaterialInfo.value[applyPlanInfo.value.material_id] && purchasedMaterialInfo.value[applyPlanInfo.value.material_id].quantity) || 0;
				// 判断所有物资不能超过计划
				if (summaryQuantity > applyPlanQuantity) {
					proxy.$message.error("物资数量不能超过计划数量");
					return;
				}
				// 判断所有物资不能超过 计划-已采购
				if (summaryQuantity > applyPlanQuantity - purchasedQuantity) {
					proxy.$message.error("物资数量不能超过剩余可采购数量");
					return;
				}

				// const { fangliang, luodu, changdu, add_time, supplier_id, supplier_name } = formState.value
				// params.materials = [{
				// 	fangliang,
				// 	luodu,
				// 	changdu,
				// 	add_time,
				// 	supplier_id,
				// 	supplier_name,
				// 	id: applyPlanInfo.value.material_id,
				// 	model: applyPlanInfo.value.type
				// }]
				params.materials = params.materials.map(item => {
					const data = { ...item };
					// 统一规范 quantity 赋值fangliang
					data.quantity = data.fangliang;
					data.model = modelOptions.value.find(target => target.id === data.id).model;
					data.art_indexes = [];
					if (data.art_gonghao_ids) {
						const artIndexes = artIndexesMap.value[item.contract_id];
						for (const gonghao_id of data.art_gonghao_ids) {
							data.art_indexes.push({
								gonghao_id,
								price: artIndexes.find(i => i.value === gonghao_id)?.price,
							})
						}
					}
					data.art_indexes = data.art_indexes.length ? JSON.stringify(data.art_indexes) : null;
					delete data.art_gonghao_ids;
					return data;
				});
				params.materials = JSON.stringify(params.materials);
			}

			params.apply_plan_id = applyPlanInfo.value.id;
			params.project_id = applyPlanInfo.value.project_id;
			params.type = route.query.type;
			params.id = currentEditItemId.value;

			Modal.confirm({
				title: "操作确认?",
				content: "您确定要提交当前采购申请吗，请确认",
				onOk() {
					submitLoading.value = true;
					post("purchaseOrder/save", params)
						.then(() => {
							if (params.id) {
								proxy.$message.success("采购单修改成功", 1);
							} else {
								proxy.$message.success("采购单创建成功", 1);
							}
							submitLoading.value = false;
							closeTab("/purchase/order/list");
						})
						.catch(err => {
							submitLoading.value = false;
							proxy.$message.error(err);
						});
				}
			});
		})
		.catch(err => {
			proxy.$message.error(err.message);
			submitLoading.value = false
			throw err;
		});
};

// 修改采购方量
function changeCGFangliang(fangliang, record) {
	if (!fangliang) return;
	// if (parseFloat(fangliang) > parseFloat(applyPlanInfo.value.materials[0].fangliang)) {
	// 	proxy.$message.error("采购方量不能大于预约方量");
	// 	fangliang = parseFloat(applyPlanInfo.value.materials[0].fangliang);
	// }
	record.fangliang = fangliang;
	record.cg_fangliang = fangliang;
}

const deleteMaterialModel = index => {
	formState.value.materials.splice(index, 1);
};

const closeTab = inject("closeTab");
</script>

<style scoped lang="scss">
.container {
	background: #fff;
	padding: 20px;

	:deep(.ant-table-cell) .ant-form-item {
		margin-bottom: 0;

		.ant-form-item-explain {
			position: absolute;
			bottom: -24px;
		}
	}

	:deep(.ant-form-item) {
		margin-bottom: 0;
	}
}
</style>
